package com.daiyang.campus_lucky_draw.service.activitystatus.Impl;

import com.daiyang.campus_lucky_draw.common.enums.ActivityPrizeStatusEnum;
import com.daiyang.campus_lucky_draw.common.enums.ActivityStatusEnum;
import com.daiyang.campus_lucky_draw.common.enums.ActivityUserStatusEnum;
import com.daiyang.campus_lucky_draw.common.error.ServiceErrorCodeConstants;
import com.daiyang.campus_lucky_draw.common.exception.ServiceException;
import com.daiyang.campus_lucky_draw.service.ActivityService;
import com.daiyang.campus_lucky_draw.service.activitystatus.ActivityStatusManager;
import com.daiyang.campus_lucky_draw.service.activitystatus.operater.AbstractActivityOperator;
import com.daiyang.campus_lucky_draw.service.dto.ConvertActivityStatusDTO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Component
public class ActivityStatusManagerImpl implements ActivityStatusManager {
    private Logger logger = LoggerFactory.getLogger(ActivityStatusManagerImpl.class);

    //Spring 会自动装配实现了AbstractActivityOperator接口的类
    //并将其注册到OperatorMap中，key为类名（首字母小写）
    @Autowired
    private Map<String, AbstractActivityOperator> operatorMap;
    @Autowired
    private ActivityService activityService;
    /**
     * 处理活动奖品人员状态
     * @param convertActivityStatusDTO
     */
    @Override
    public void handlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        if(CollectionUtils.isEmpty(operatorMap)) {
            logger.warn("OperatorMap is 为空");
            return;
        }
        // map 1 人员 2 奖品 3 活动
        Map<String, AbstractActivityOperator> currMap=new HashMap<>(operatorMap);
        Boolean update=false;
        //先处理人员，奖品
        update= processCovertStatus(convertActivityStatusDTO,currMap,1);
        
        
        
        //后处理活动（依赖奖品是否被抽完）
        update=processCovertStatus(convertActivityStatusDTO,currMap,2)||update;


        //不管奖品活动哪一个状态改变，我们都要更新缓存
        if(update) {
            activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
        }

    }

    @Override
    public void rollbackHandlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
       // operatorMap：活动、奖品、人员
        // 活动是否需要回滚？？ 绝对需要，
        // 原因：奖品都恢复成INIT，那么这个活动下的奖品绝对没抽完
        for(AbstractActivityOperator operator:operatorMap.values()){
            operator.convert(convertActivityStatusDTO);
        }

        //更新缓存
        activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
    }







    private Boolean processCovertStatus(ConvertActivityStatusDTO convertActivityStatusDTO, Map<String, AbstractActivityOperator> currMap, Integer i) {
        //遍历currMap
        Iterator<Map.Entry<String, AbstractActivityOperator>> iterator = currMap.entrySet().iterator();
        Boolean update=false;
        while(iterator.hasNext()) {
            AbstractActivityOperator operator = iterator.next().getValue();
            //判断需要转化吗
           if(!operator.sequence().equals(i)
                   ||!operator.needCovert(convertActivityStatusDTO)) {
               continue;
           }

           //需要转化
            if(!operator.convert(convertActivityStatusDTO)) {
                logger.error("operator {} convert failed",operator.getClass().getName());
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_STATUS_CONVERT_ERROR);
            }

            //currMap删除当前的Operator
            iterator.remove();
            update=true;

        }
        return  update;


    }
}
